<template>
  <div class="property-form">
    <draggable :list="conditions" item-key="id" handle=".drag-handle" class="no-indent" @end="onDragEnd">
      <template #item="{ element: condition, index }">
        <li class="card-collapse-item">
          <div class="condition-item">
            <div v-if="condition.type !== 'default'" class="condition-header">
              <SlidingVertical class="drag-handle" :size="16" />
              <el-select v-model="condition.type" class="condition-type-select" size="small"
                @change="handleTypeChange(index)">
                <el-option v-for="item in conditionTemplates" :label="item.name" :value="item.type" />
              </el-select>
              <Delete class="delete-icon ml-auto" @click="removeCondition(index)" />
            </div>
            <div v-else class="condition-header">
              <SlidingVertical class="drag-handle" :size="16" />
              <div class="condition-type-select" size="small">{{ condition.name }}</div>
            </div>

            <div class="condition-content" v-if="condition.type === 'custom'">
              <el-form :model="condition" class="condition-form">
                <el-form-item label="条件名称" class="form-row">
                  <div class="input-group">
                    <el-input v-model="condition.name" size="small" @blur="() => handleConditionBlur(condition.id)"
                      placeholder="请输入条件名称" />
                  </div>
                </el-form-item>
                <!-- 可以在这里添加更多的表单项 -->
              </el-form>
            </div>
          </div>
        </li>
      </template>
    </draggable>
    <el-button type="primary" @click="addCondition">添加条件</el-button>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { Delete, SlidingVertical } from "@icon-park/vue-next";
import { ElMessage } from "element-plus";
import { nanoid } from "nanoid";
import { useVueFlow } from "@vue-flow/core";
import { conditionTemplates, type ConditionInfo } from "@/types/types";
import draggable from "vuedraggable";

const props = defineProps({
  node: Object as Node,
});

const { updateNode, updateEdge, getHandleConnections, removeEdges } = useVueFlow();

const conditions = computed(() => props.node?.data?.conditions || []);

const updateConditions = (conditions: ConditionInfo[]) => {
  updateNode(props.node.id, {
    data: {
      ...props.node.data,
      conditions,
    },
  });
};

const updateEdges = () => {
  if (!props.node || !conditions.value) return; // 添加空值检查

  // 使用forEach遍历conditions数组（修复：将for...in改为forEach）
  conditions.value.forEach((condition) => {
    // 查找与当前条件句柄连接的边（修复：使用condition.id作为句柄ID）
    const connectedEdges = getHandleConnections({
      nodeId: props.node.id,
      type: 'source',
      id: condition.id,
    })

    //由于调整handle顺序后，vue-flow无法正确连接边，所以只能删除。
    connectedEdges.forEach(edge => {
      removeEdges(edge.edgeId)
    })
  });
};

const removeCondition = (index: number) => {
  const condition = conditions.value[index];
  if (condition.type == "default") {
    return ElMessage.error("默认条件不能删除");
  }

  const newConditions = [...conditions.value];
  newConditions.splice(index, 1);

  updateConditions(newConditions);
  updateEdges();
};

// 添加新条件
const addCondition = () => {
  const newCondition = {
    id: "condition-" + nanoid(),
    type: "custom",
    name: "自定义条件",
    multiplicable: true,
  };

  updateConditions([...conditions.value, newCondition]);
};

const handleConditionBlur = (conditionId: string) => { };

const handleTypeChange = (index: number) => {
  const newConditions = [...conditions.value];
  const type = newConditions[index].type as keyof typeof conditionTemplates;
  const newCondition = conditionTemplates[type];

  if (newCondition) {
    newCondition.id = "condition-" + nanoid();
    newConditions[index] = { ...newCondition };
    updateConditions(newConditions);
  }
};

// 拖拽结束时的回调
const onDragEnd = () => {
  updateConditions(conditions.value);
  updateEdges();
};
</script>

<style scoped>
/* 头部区域样式 */
.condition-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background-color: #f0f2f5;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  min-height: 40px;
}

.condition-title {
  font-weight: bold;
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.delete-icon {
  margin-left: 10px;
  width: 16px;
  height: 16px;
  color: #ff4d4f;
  cursor: pointer;
  transition: color 0.2s;
  flex-shrink: 0;
}

.delete-icon:hover {
  color: #d9363e;
}

/* 表单内容区域 */
.condition-content {
  padding: 15px;
  background-color: #ffffff;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  border-top: 1px solid #ebeef5;
}

/* 表单行样式 - 水平布局 */
.form-row {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

/* 表单标签样式 */
:deep(.form-row .el-form-item__label) {
  width: 80px;
  /* 固定标签宽度 */
  text-align: right;
  padding-right: 15px;
  font-size: 13px;
  color: #606266;
  justify-content: flex-start;
}

/* 表单内容区域 */
:deep(.form-row .el-form-item__content) {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: center;
}

/* 输入框组样式 */
.input-group {
  display: flex;
  gap: 10px;
  align-items: center;
  width: 100%;
}

/* 输入框样式 */
.input-group :deep(.el-input) {
  flex-grow: 1;
}

/* 编辑按钮样式 */
.edit-icon {
  width: 16px;
  height: 16px;
  color: #409eff;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.edit-icon:hover {
  color: #0084ff;
}

/* 保存按钮样式 */
.save-icon {
  width: 16px;
  height: 16px;
  color: #67c23a;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.save-icon:hover {
  color: #5daf34;
}

/* 卡片项整体布局 */
.card-collapse-item {
  display: flex;
  flex-direction: column;
  background-color: #f7f9fc;
  border-radius: 6px;
  overflow: hidden;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.card-collapse-item:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

/* 主容器样式 */
.property-form {
  width: 100%;
  padding: 20px 15px;
}

/* 添加按钮样式 */
.property-form .el-button {
  width: 100%;
  margin-top: 10px;
}

/* 表单项间距优化 */
.condition-form .form-row:last-child {
  margin-bottom: 5px;
}

.condition-type-select {
  width: 180px;
}

/* 拖拽手柄样式 */
.drag-handle {
  color: #a0a0a0;
  cursor: grab;
  transition: color 0.2s;
  flex-shrink: 0;
}

.drag-handle:hover {
  color: #409eff;
}
</style>
